//
//  UPCustomTabBarView.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/17.
//

#import "UPCustomTabBarView.h"
#import "UPCustomTabBarItem.h"


@interface UPCustomTabBarView ()

@property (nonatomic, strong) UIStackView *stackView;
@property (nonatomic, strong) NSArray<UPCustomTabBarItem *> *items;
@property (nonatomic, strong) NSLayoutConstraint *heightConstraint;

@end

@implementation UPCustomTabBarView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupView];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self setupView];
    }
    return self;
}

- (void)setupView {
//    self.backgroundColor = [UIColor whiteColor];
//    
//    // 阴影效果
//    self.layer.shadowColor = [UIColor blackColor].CGColor;
//    self.layer.shadowOffset = CGSizeMake(0, -1);
//    self.layer.shadowOpacity = 0.1;
//    self.layer.shadowRadius = 5;
//
    _bgImageView = [[UIImageView alloc] init];
    _bgImageView.image = [UIImage imageNamed:@"tabbar_item1"];
    [self addSubview:_bgImageView];
    _bgImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:@[
        [_bgImageView.leadingAnchor constraintEqualToAnchor:self.leadingAnchor],
        [_bgImageView.trailingAnchor constraintEqualToAnchor:self.trailingAnchor],
        [_bgImageView.topAnchor constraintEqualToAnchor:self.topAnchor],
        [_bgImageView.bottomAnchor constraintEqualToAnchor:self.bottomAnchor]
    ]];
    
    // 默认值
    _normalColor = [UIColor grayColor];
    _selectedColor = [UIColor systemBlueColor];
    _itemSpacing = 10;
    _barHeight = 49;
    
    // 创建 StackView
    _stackView = [[UIStackView alloc] init];
    _stackView.axis = UILayoutConstraintAxisHorizontal;
    _stackView.distribution = UIStackViewDistributionFillEqually;
    _stackView.alignment = UIStackViewAlignmentFill;
    _stackView.spacing = _itemSpacing;
    _stackView.translatesAutoresizingMaskIntoConstraints = NO;
    
    [self addSubview:_stackView];
    
    // 添加约束
    [NSLayoutConstraint activateConstraints:@[
        [_stackView.leadingAnchor constraintEqualToAnchor:self.leadingAnchor],
        [_stackView.trailingAnchor constraintEqualToAnchor:self.trailingAnchor],
        [_stackView.topAnchor constraintEqualToAnchor:self.topAnchor],
        [_stackView.bottomAnchor constraintEqualToAnchor:self.bottomAnchor]
    ]];
    
    _heightConstraint = [self.heightAnchor constraintEqualToConstant:_barHeight + self.safeAreaInsets.bottom];
    _heightConstraint.active = YES;
}

- (void)setupItems {
    // 清除现有 items
    for (UPCustomTabBarItem *item in _items) {
        [item removeFromSuperview];
    }
    _items = @[];
    
    // 确保 titles 和 icons 数量一致
    NSInteger count = _itemTitles.count;
    
    NSMutableArray *mutableItems = [NSMutableArray array];
    for (NSInteger i = 0; i < count; i++) {
        UPCustomTabBarItem *item = [[UPCustomTabBarItem alloc] init];
        if (i < _itemIcons.count) {
            item.icon = _itemIcons[i];
        }

        if (i < _selectedItemIcons.count) {
            item.selectedIcon = _selectedItemIcons[i];
        }
        item.title = _itemTitles[i];
        item.tag = i;
        item.selected = (i == _selectedIndex);
        [item addTarget:self action:@selector(itemTapped:) forControlEvents:UIControlEventTouchUpInside];
        
        [_stackView addArrangedSubview:item];
        [mutableItems addObject:item];
    }
    
    _items = [mutableItems copy];
    [self updateItemsAppearance];
}

- (void)updateItemsAppearance {
    for (NSInteger i = 0; i < _items.count; i++) {
        UPCustomTabBarItem *item = _items[i];
        item.normalColor = _normalColor;
        item.selectedColor = _selectedColor;
        item.selected = (i == _selectedIndex);
    }
}

- (void)updateSelection {
    for (NSInteger i = 0; i < _items.count; i++) {
        _items[i].selected = (i == _selectedIndex);
    }
}

- (void)itemTapped:(UPCustomTabBarItem *)sender {
    NSInteger newIndex = sender.tag;
    if (newIndex == _selectedIndex) return;
    
    if (newIndex > 0) {
        __weak typeof(self) weakSelf = self;
        
        [[UPLocationManager sharedManager] upRequestLocationPermissionWithCompletion:^(BOOL granted) {
            
            if ([AppConfig sharedInstance].appCountryEnv == AppCountryEnvIndonesia && !granted) {
                return;
            }
            [weakSelf updateSelectionForIndex:newIndex];
        }];
    } else {
        [self updateSelectionForIndex:newIndex];
    }
}

- (void)updateSelectionForIndex:(NSInteger)newIndex {
    for (UPCustomTabBarItem *item in _items) {
        item.selected = NO;
    }
    _items[newIndex].selected = YES;
    _selectedIndex = newIndex;
    [self.delegate tabBar:self didSelectItemAtIndex:newIndex];
}

- (void)safeAreaInsetsDidChange {
    [super safeAreaInsetsDidChange];
    _heightConstraint.constant = _barHeight + self.safeAreaInsets.bottom;
}

#pragma mark - Property Setters

- (void)setItemTitles:(NSArray<NSString *> *)itemTitles {
    _itemTitles = [itemTitles copy];
    [self setupItems];
}

- (void)setItemIcons:(NSArray<UIImage *> *)itemIcons {
    _itemIcons = [itemIcons copy];
    [self setupItems];
}

- (void)setSelectedItemIcons:(NSArray<UIImage *> *)selectedItemIcons {
    _selectedItemIcons = [selectedItemIcons copy];
    [self setupItems];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    _selectedIndex = selectedIndex;
    [self updateSelection];
}

- (void)setNormalColor:(UIColor *)normalColor {
    _normalColor = normalColor;
    [self updateItemsAppearance];
}

- (void)setSelectedColor:(UIColor *)selectedColor {
    _selectedColor = selectedColor;
    [self updateItemsAppearance];
}

- (void)setItemSpacing:(CGFloat)itemSpacing {
    _itemSpacing = itemSpacing;
    _stackView.spacing = itemSpacing;
}

- (void)setBarHeight:(CGFloat)barHeight {
    _barHeight = barHeight;
    _heightConstraint.constant = barHeight + self.safeAreaInsets.bottom;
}

@end
